<template>
  <div class="book" v-loading="mainLoading">
    <div class="book-header">
      <div class="search">
        <el-input
          v-model="searchValue"
          placeholder="请输入关键词"
          :clearable="true"
          size="mini"
          class="search-ipt"
        ></el-input>
        <el-button type="primary" size="mini" @click="search">搜索</el-button>
        <el-button size="mini" @click="reset">重置</el-button>
      </div>
      <div class="insert">
        <el-link type="info" @click="insertJudgment"
          >没找到想要的？快来新添一个吧~</el-link
        >
      </div>
    </div>
    <div class="book-main" v-if="dataList.length > 0">
      <CommonItem :dataList="dataList"></CommonItem>
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        :total="total"
        :pager-count="7"
        style="text-align: right; margin-top: 20px"
      >
      </el-pagination>
    </div>
    <div class="empty" v-else="!dataList.length > 0">
      <el-empty description="暂无数据，快去添加吧！"
        ><span @click="insertJudgment">点我添加</span>
      </el-empty>
    </div>
    <!-- dialog -->
    <el-dialog
      title="新增图书"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form :rules="rulesInsert" ref="insertForm" :model="insertForm">
        <el-form-item label="书名" prop="title" :label-width="formLabelWidth">
          <el-input v-model="insertForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="auhnor" :label-width="formLabelWidth">
          <el-input v-model="insertForm.auhnor" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="出版社"
          prop="publishingHouse"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="insertForm.publishingHouse"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="原作名"
          prop="formerly"
          :label-width="formLabelWidth"
        >
          <el-input v-model="insertForm.formerly" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版年" prop="year" :label-width="formLabelWidth">
          <el-date-picker
            v-model="insertForm.year"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="页数" prop="pages" :label-width="formLabelWidth">
          <el-input v-model="insertForm.pages" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="定价" prop="price" :label-width="formLabelWidth">
          <el-input v-model="insertForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn" :label-width="formLabelWidth">
          <el-input v-model="insertForm.isbn" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
      <div class="cover">
        <img v-show="insertForm.cover" :src="insertForm.cover" alt="" />
        <el-upload
          action="zhanweifu"
          :auto-upload="false"
          :on-change="changeFile"
          :show-file-list="false"
        >
          <el-link
            v-show="!insertForm.cover"
            type="info"
            :underline="false"
            class="text"
            >上传封面</el-link
          >
        </el-upload>
        <i
          class="close"
          v-show="insertForm.cover"
          @click="insertForm.cover = ''"
          >X</i
        >
        <div
          class="uploadLoading"
          v-loading="uploadLoading"
          element-loading-text="正在上传封面"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.7)"
        ></div>
      </div>
      <div class="img-help">
        <a href="https://docsmall.com/image-compress" target="_blank"
          >图片太大，快来压缩试试~</a
        >
      </div>
      <div class="context">
        <el-input
          type="textarea"
          :autosize="{ minRows: 10, maxRows: 10 }"
          placeholder="请输入内容详情"
          v-model="insertForm.detail"
        >
        </el-input>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonItem from "@/components/CommonItem.vue";
import { uploadFile } from "@/api/common.js";
import { getBookList, insertBook } from "@/api/book";
import { isValidToken } from "@/utils/checkTokenValid";
export default {
  name: "BookView",
  data() {
    return {
      // 页数
      page: 1,
      // 每页条数
      pageSize: 10,
      // 当前页数
      currentPage: 1,
      // 总记录数
      total: 0,
      // 搜索关键词
      searchValue: "",
      dataList: [],
      // 对话框的显示与关闭
      dialogFormVisible: false,
      mainLoading: false,
      uploadLoading: false,
      insertLoading: false,
      // 新增表单数据
      insertForm: {
        title: "",
        isbn: "",
        auhnor: "",
        publishingHouse: "",
        formerly: "",
        year: "",
        pages: "",
        price: "",
        detail: "",
        cover: "",
      },
      // 新增校验
      rulesInsert: {
        title: [{ required: true, message: "请输入书名", trigger: "blur" }],
        auhnor: [{ required: true, message: "请输入作者", trigger: "blur" }],
        publishingHouse: [
          { required: true, message: "请输入出版社", trigger: "blur" },
        ],
        formerly: [
          { required: true, message: "请输入原作名", trigger: "blur" },
        ],
        year: [{ required: true, message: "请输入出版年", trigger: "blur" }],
        pages: [{ required: true, message: "请输入页数", trigger: "blur" }],
        price: [{ required: true, message: "请输入定价", trigger: "blur" }],
        isbn: [{ required: true, message: "请输入ISBN", trigger: "blur" }],
      },
      formLabelWidth: "120px",
    };
  },
  components: {
    CommonItem,
  },
  created() {
    this.getList();
  },
  methods: {
    search() {
      if (!this.searchValue) {
        this.$message({
          type: "warning",
          message: "搜索内容不能为空！",
        });
        return;
      }
      this.getList();
    },
    // 重置
    reset() {
      this.page = 1;
      this.pageSize = 10;
      this.searchValue = "";
      this.getList();
    },
    // 新增判断
    async insertJudgment() {
      const flag = await isValidToken();
      if (!flag) {
        this.$router.push("/login");
        this.$message.error("请先登录！");
        return;
      }
      this.dialogFormVisible = true;
    },
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          if (this.insertForm.cover == "") {
            this.$message.error("请上传封面");
            return;
          }
          if (this.insertForm.detail == "") {
            this.$message.error("请输入详情");
            return;
          }
          try {
            this.insertLoading = true;
            const res = await insertBook(this.insertForm);
            this.dialogFormVisible = false;
            this.getList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 获取书籍列表
    async getList() {
      this.mainLoading = true;
      try {
        const res = await getBookList(
          this.page,
          this.pageSize,
          this.searchValue
        );
        this.dataList = res.data.records;
        this.total = res.data.total;
      } catch {
        this.$message.error("获取列表失败");
      } finally {
        this.mainLoading = false;
      }
    },
    // 当前页发生改变时触发
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    // 选择文件，上传封面
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      let formData = new FormData();
      // 拿到存在fileList中的文件存放到formData中
      formData.append("file", file.raw);
      const res = await uploadFile(formData);
      this.uploadLoading = false;
      this.insertForm.cover = res.data;
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 关闭对话框时清空表单数据和校验状态
    closeDialog() {
      this.insertForm = {
        title: "",
        isbn: "",
        auhnor: "",
        publishingHouse: "",
        formerly: "",
        year: "",
        pages: "",
        price: "",
        detail: "",
        cover: "",
      };
      this.insertLoading = false;
      this.uploadLoading = false;
      this.$refs.insertForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.book {
  width: 100%;
  .book-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      width: 26%;
      display: flex;
      .search-ipt {
        margin: 0 10px;
      }
    }
  }
  .empty {
    span {
      cursor: pointer;
    }
  }
}
// el-dialog样式
/deep/.el-dialog {
  width: 46%;
  position: relative;
  .cover {
    position: absolute;
    top: 12%;
    right: 14%;
    width: 20%;
    height: 28%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
    img {
      width: 100%;
      height: 100%;
      // 当src为空时，设置透明度为0，使其不可见
      &[src=""],
      &:not([src]) {
        opacity: 0;
      }
    }
    .close {
      position: absolute;
      z-index: 9999;
      top: 0;
      right: 0;
      width: 20px;
      height: 20px;
      background-color: #fff;
      display: inline-block;
      text-align: center;
      line-height: 16px;
      font-style: normal;
      border: 2px solid;
      cursor: pointer;
      border-radius: 50%;
    }
    .text {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 9999;
    }
    .uploadLoading {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
  }
  .img-help {
    position: absolute;
    right: 12.7%;
    top: 42%;
    a {
      text-decoration: none;
      color: #aaa;
      font-size: 13px;
    }
  }
  .context {
    position: absolute;
    bottom: 19.6%;
    right: 3%;
    width: 42%;
    margin: 0 auto;
    margin-top: 5%;
  }
}
.el-form {
  width: 50%;
}
/deep/.el-input__inner {
  width: 14vw;
}
</style>